package com.feituan.wx.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feituan.core.error.SystemCode;
import com.feituan.core.exception.BusinessException;
import com.feituan.core.persistence.mapper.MerchantMapper;
import com.feituan.core.persistence.service.IProductService;
import com.feituan.core.persistence.service.IUserCouponService;
import com.feituan.core.persistence.service.IUserService;
import com.feituan.core.pojo.entity.User;
import com.feituan.core.pojo.entity.UserCoupon;
import com.feituan.core.pojo.response.Response;
import com.feituan.core.pojo.response.UserRes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaohu
 * @since 2024-05-09
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController extends BaseController{
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService iUserService;

    @Resource
    private IUserCouponService userCouponService;

    @Autowired
    private IProductService iProductService;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private WxMaService wxService;
    @PostMapping("/login")
    @ApiOperation("登录或者注册")
    public Response<Boolean> login(@RequestBody User user) {
        if(StringUtils.isEmpty(user.getWxid()) ){
            return response(false);
        }
        User inUser = iUserService.lambdaQuery().eq(User::getWxid,user.getWxid()).one();
        if(inUser != null){
            User updateUser = new User();
            updateUser.setId(inUser.getId());
            updateUser.setLatestLoginTime(Calendar.getInstance().getTime());
            iUserService.updateById(updateUser);
        }else {
            user.setLatestLoginTime(Calendar.getInstance().getTime());
            user.setCreateTime(Calendar.getInstance().getTime());
            iUserService.save(user);
        }
        return response(true);
    }

    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    public Response<User> update(User user) {
        logger.info("user update request:{}",JSON.toJSON(user));
        if(user.getId() == null){
            return Response.success(null);
        }
        User inUser = iUserService.getById(user.getId());
        if(inUser != null){
            User updateUser = new User();
            BeanUtils.copyProperties(user,updateUser);
            updateUser.setId(inUser.getId());
            updateUser.setLatestLoginTime(Calendar.getInstance().getTime());
            iUserService.updateById(updateUser);
            return Response.success(updateUser);
        }else {
            return Response.success(null);
        }
    }


    /**
     * 修改用户积分
     * @param user user
     * @return
     */
    @PostMapping("/updateIntegration")
    public Response<Boolean> updateIntegration(User user) {
        return Response.success(this.iUserService.updateById(user));
    }
     /**
     * 微信登录
     *
     * @param request
     *            请求对象
     * @return 登录结果
     */
    @PostMapping("login_by_wx")
    public Response<UserRes> loginByWeixin(String code,  String phone, HttpServletRequest request) {
        logger.error("wx login request code:{}",code);
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            logger.info("login wx result:{}", JSON.toJSON(result));
        } catch (Exception e) {
            logger.error("wx login error",e);
        }

        if (sessionKey == null || openId == null) {
            throw new BusinessException(SystemCode.WX_LOGIN_ERROR);
        }

        User inUser = iUserService.lambdaQuery().eq(User::getWxid,openId).one();
        Boolean newUser = null;
        if(inUser != null){
            newUser = false;
            User updateUser = new User();
            updateUser.setId(inUser.getId());
            updateUser.setPhone(phone);
            updateUser.setLatestLoginTime(Calendar.getInstance().getTime());
            iUserService.updateById(updateUser);
        }else {
            newUser = true;
            inUser =new User();
            inUser.setName("微信用户");
            inUser.setSex(0);
            inUser.setWxid(openId);
            inUser.setLatestLoginTime(Calendar.getInstance().getTime());
            inUser.setCreateTime(Calendar.getInstance().getTime());
            inUser.setPhone(phone);
            iUserService.save(inUser);
        }
        logger.info("wx login response:{}",inUser);
        UserRes userRes = new UserRes();
        BeanUtils.copyProperties(inUser, userRes);
        userRes.setNewUser(newUser);
        return Response.success(userRes);
    }
    /**
     * 获取微信手机号
     *
     * @param request
     *            请求对象
     * @return 登录结果
     */
    @PostMapping("get_phone_wx")
    @ApiOperation("获取微信手机号")
    public Response<String> getPhoneByWeixin(String code, HttpServletRequest request) {
        logger.error("wx getPhoneByWeixin code:{}",code);
        try {
            WxMaPhoneNumberInfo result = this.wxService.getUserService().getPhoneNoInfo(code);
            logger.info("getPhoneNoInfo wx result:{}", JSON.toJSON(result));
            return  Response.success(result.getPhoneNumber());

        } catch (Exception e) {
            logger.error("wx getPhoneByWeixin error",e);
        }

        return Response.success(null);
    }


    /**
     * 小程序端通过userId获取用户信息
     * @param userId userId
     * @return
     */
    @PostMapping("/getUserInfoByUserId")
    public  Response<UserRes> selectByUserId(Long userId) {
        User user = iUserService.selectById(userId);
        UserRes userRes = new UserRes();
        BeanUtils.copyProperties(user, userRes);
        LambdaQueryWrapper<UserCoupon> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCoupon::getUserId, userId);
        qw.eq(UserCoupon::getCouponStatus, 0);
        List<UserCoupon> userCoupons = userCouponService.getBaseMapper().selectList(qw);
        if (CollectionUtils.isEmpty(userCoupons)) {
            userRes.setCouponNum(0);
        } else {
            userRes.setCouponNum(userCoupons.size());
        }
        return Response.success(userRes);
    }

    /**
     * 根据用户ID获取集星数量
     * @param userId userId
     */
    @PostMapping("/selectStarsByUserId")
    public Response<Integer> selectStarsByUserId(Long userId) {
        return Response.success(iUserService.selectStarsByUserId(userId));
    }

    /**
     * 修改用户领取新用户礼包状态
     * @param userId userId
     */
    @PostMapping("/judgeNewUser")
    private Response<Boolean> judgeNewUser(Long userId, String type) {
        return Response.success(iUserService.judgeNewUser(userId, type));
    }
}
